<template>
	<view class="uploader-box">
		<view class="uploader-box__imgs">
			<template v-if="fileList.length && preview">
				<view class="img-item" v-for="(item, idx) in fileList" :key="idx" :style="` width: ${props.width}px; height: ${props.height}px; `">
					<view class="close" @click="deleteImage(idx)">×</view>
					<view class="image-box" v-if="isImage(item.filepath)" @click="hanldePreview(idx)">
						<image :src="item.filepath" />
					</view>
					<view class="image-box" v-else-if="isVideo(item.filepath)" @click="hanldePreview(idx)">
						<view class="icon">
							<IconFont  name="play-starts" size="24" color="#fff"></IconFont>
						</view>
						<image :src="`${item.filepath}?x-oss-process=video/snapshot,t_100,f_jpg,w_800,h_600,m_fast`" />
					</view>
					<view class="image-box" v-else @click="handlePreviewFile(item.filepath)">
						<view class="uploader-box__icon">
							<img :src="getFileTypeIcon(item.filepath)" />
						</view>
					</view>
				</view>
			</template>
			<!-- uploadFileFromDevice uploadFileFromMessage -->
			<view v-if="$slots.icon" @click="handleUploadFile">
				<slot name="icon"></slot>
			</view>
			<template v-else>
				<view
					class="img-item"
					:style="` width: ${props.width}px; height: ${props.height}px; `"
					@click="handleUploadFile"
					v-if="fileList.length < limitNum"
				>
					<IconFont name="uploader" size="20"></IconFont>
				</view>
			</template>
		</view>

		<!-- <view class="uploader-box__message" v-if="showMessageUpload && fileList.length < limitNum" @click="handleUploadFile">
			<text>未找到？</text>
			<text style="text-decoration: underline; color: #007aff">从微信消息中选择</text>
		</view> -->
	</view>
</template>

<script setup>
import { watch, ref, getCurrentInstance } from 'vue';
import { uploadFile, chooseFileFromMessage, chooseFileFromCamera, chooseFileFromAlbum } from '@/hook/useWechatFile';
import iconPdf from '@/static/icon_pdf.png';
import iconDoc from '@/static/icon_doc.png';
import iconXls from '@/static/icon_xls.png';
import iconFile from '@/static/icon_file.png';

const { proxy } = getCurrentInstance();
// const defaultDir = `upload/${proxy.$storage.get('manufacturerId')}`
const emit = defineEmits(['update:duration', 'update:fileType', 'on-success', 'after-upload']);
const props = defineProps({
	modelValue: {
		type: [Array, String],
		default: []
	},
	multiple: {
		type: Boolean,
		default: false
	},
	limitNum: {
		type: Number,
		default: 1
	},
	preview: {
		type: Boolean,
		default: true
	},
	dir: {
		type: String,
		required: true
	},
	height: { type: String, default: '80' },
	width: { type: String, default: '80' },
	// 是否显示从微信消息中选择
	showMessageUpload: { type: Boolean, default: false }
});

const fileList = ref([]);

function isVideo(url) {
	const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.mkv', '.flv', '.webm'];
	return videoExtensions.some(ext => url.toLowerCase().endsWith(ext));
}

function isImage(url) {
	const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp'];
	return imageExtensions.some(ext => url.toLowerCase().endsWith(ext));
}

const handlePreviewFile = url => {
	wx.downloadFile({
		url: url,
		success: function (res) {
			var filePath = res.tempFilePath;

			wx.openDocument({
				filePath: filePath,
				showMenu: true,
				success: function (res) {},
				fail: function (err) {}
			});
		}
	});
}

function getFileTypeIcon(url) {
	const fileTypeIcon = {
		pdf: iconPdf,
		doc: iconDoc,
		docx: iconDoc,
		xls: iconXls,
		xlsx: iconXls,
		none: iconFile
	};

	const fileType = url.split('.').pop();

	return fileTypeIcon[fileType] || fileTypeIcon.none;
}

const deleteImage = idx => {
	fileList.value.splice(idx, 1);
	emit('update:modelValue', fileList.value.map(i => i.filepath).join(','));
};

const doUpload = async file => {
	const uploadRes = await uploadFile({
		file: {
			name: '',
			path: file.tempFilePath,
			extname: file.tempFilePath.split('.').pop()
		},
		props: {
			key: props.dir
		},
		useOriginalFileName: false
	});

	console.log('uploadRes', uploadRes);

	fileList.value.push(uploadRes);
	emit('update:modelValue', fileList.value.map(i => i.filepath).join(','));
	emit('update:duration', file?.duration ? parseInt(file.duration) : 0);
	emit('update:fileType', file.fileType);
	emit('on-success', uploadRes);
	emit('after-upload');
};

const uploadFileFromAlbum = async () => {
	const res = await chooseFileFromAlbum();
	const file = res.tempFiles[0];

	doUpload(file);
};

const uploadFileFromCamera = async () => {
	const res = await chooseFileFromCamera();
	const file = res.tempFiles[0];

	doUpload(file);
};

const uploadFileFromMessage = async () => {
	const res = await chooseFileFromMessage({ type: 'all', count: 1 });
	const file = res.tempFiles[0];

	const uploadFile = {
		fileType: file.type,
		tempFilePath: file.path,
		size: file.size,
	}
	doUpload(uploadFile);
};

const hanldePreview = idx => {
	wx.previewMedia({
		sources: fileList.value.map(item => {
			return {
				url: item.filepath,
				type: isVideo(item.filepath) ? 'video' : 'image',
				poster: `${item.filepath}?x-oss-process=video/snapshot,t_100,f_jpg,w_800,h_600,m_fast`
			};
		}),
		current: idx
	});
};

const handleUploadFile = () => {
	wx.showActionSheet({
		itemList: ['拍摄', '从相册中选择', '从微信消息中选择'],
		success(res) {
			const tapIndex = res.tapIndex; // 用户点击的选项索引
			if (tapIndex === 0) {
				// 从设备中选择
				uploadFileFromCamera();
			} else if (tapIndex === 1) {
				// 从相册中选择
				uploadFileFromAlbum();
			} else if (tapIndex === 2) {
				// 从微信消息中选择
				uploadFileFromMessage();
			}
		},
		fail() {
			// wx.showToast({
			// 	title: '取消',
			// 	icon: 'none'
			// });
		}
	});
};

watch(
	() => props.modelValue,
	val => {
		if (!val) return;

		if (typeof val === 'string') {
			const fileArray = val.split(',');

			fileList.value = fileArray.length
				? fileArray.map(i => {
						return {
							filepath: i,
							filename: i
						};
				  })
				: [];
		} else {
			// 目前都以逗号隔开的字符串来表示
		}
	},
	{ immediate: true }
);
</script>

<style lang="scss">
.uploader-box {
	width: 100%;
	height: 100%;
	// display: flex;
	// align-items: center;
	//   justify-content: center;

	&__icon {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;

		image {
			width: 32px !important;
			height: 32px !important;
		}
	}

	.img-icon {
		width: 90px;
		height: 90px;
		background-color: #f7f4f4;
		border-radius: 4px;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		margin-right: 4px;
		img {
			width: 100%;
			height: 100%;
			object-fit: cover;

			&.icon-img {
				width: 20px;
				height: 20px;
				object-fit: cover;
			}
		}
	}

	&__message {
		margin-top: 4px;
	}

	&__imgs {
		display: flex;
		align-items: center;
		flex-wrap: wrap;

		.img-item {
			background-color: #f7f4f4;
			border-radius: 4px;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			margin: 0 4px 4px 0;

			.close {
				position: absolute;
				z-index: 10;
				right: 0;
				top: 0;
				width: 18px;
				height: 18px;
				color: #fff;
				font-size: 13px;
				background: #333;
				border-radius: 0 0 0 10px;
				text-align: center;
				line-height: 16px;
			}

			.image-box {
				position: relative;
				width: 100%;
				height: 100%;

				.icon {
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
					z-index: 10;
				}

				image {
					width: 100%;
					height: 100%;
					object-fit: cover;

					&.icon-img {
						width: 20px;
						height: 20px;
						object-fit: cover;
					}
				}
			}

			// &:first-child {
			//   img {
			//     width: 20px;
			//     height: 20px;
			//     object-fit: cover;
			//   }
			// }
		}
	}
}
</style>
